const { createUser, getUser, updateUserPassword } = require('../service/user.service')
const jsonwebtoken = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config.development')
const bcrypt = require('bcryptjs');
class UserController {
    // 注册
    async register(ctx, next) {
        try {
            const { username, password } = ctx.request.body;
            // 如果用户存在
            const userSelect = await getUser(username);
            if (userSelect) {
                ctx.status = 500;
                ctx.body = { code: 500, message: '用户已存在!' };
                return;
            }
            // 调用 createUser 函数创建用户
            const res = await createUser(username, password);
            ctx.body = {
                code: 200,
                message: '用户注册成功!',
                data: {
                    id: res.id,
                    username: res.username
                }
            }; // 假设 createUser 返回了用户数据  
        } catch (error) {
            ctx.status = 500; // 或其他适当的 HTTP 状态码  
            ctx.body = {code:500, message: '用户注册失败!', error: error.message };
        }
    }
    // 登录
    async login(ctx, next) {
        const { username, password } = ctx.request.body;
        const user = await getUser(username, password);
        const bcryptjsPassqord = user.password
        // 解密 第一个参数是传过来的id,第二个参数是数据库查询的加密的密码
        if (bcrypt.compareSync(password, bcryptjsPassqord)) {
            ctx.body = {
                code: 200,
                message: '登录成功!',
                data: {
                    id: user.id,
                    username: user.username,
                    token: jsonwebtoken.sign({ id: user.id, username: user.username, is_admin: user.is_admin }, JWT_SECRET, { expiresIn: '10h' })
                }
            }
        } else {
            ctx.status = 500;
            ctx.body = { code: 500, message: '用户名或密码错误!' };
        }
    }
    // 修改密码
    async updatePassword(ctx, next) {
        const id = ctx.state.user.id;
        const password = ctx.request.body.password;
        const res = await updateUserPassword(id, password, ctx.state.user.is_admin);
        if (res) {
            ctx.body = {
                code: 200,
                message: '密码修改成功!',
                data:''
            }
        } else {
            ctx.status = 500;
            ctx.body = {
                code: 500,
                message: '密码修改失败!',
                data:''
            };
        }
    }
}
module.exports = new UserController()